package leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/*
    两数之和
 */
public class Demo01 {
    public static void main(String[] args) {
        int[] nums = new int[]{2, 7, 11, 15};
        System.out.println(Arrays.toString(twoSum1(nums, 9)));
    }

    public static int[] twoSum(int arr[], int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int result[] = new int[]{-1, -1};
        for (int i = 0; i < arr.length; i++) {
            map.put(i, arr[i]);
        }
        int c = 0;
        for (int key : map.keySet()) {
            c = target - map.get(key);
            if (map.containsValue(c)) {   //找到一组结果
                result[0] = key;
                for (int key1 : map.keySet()) {
                    if (key != key1 && map.get(key1) == c) {
                        result[1] = key1;
                    }
                }
            }
        }
        return result;
    }

    public static int[] twoSum1(int arr[], int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int result[] = new int[]{-1, -1};
        //遍历数组，将元素一次放入map集合中，在放入之前看看集合中是否有元素可以与当前元素形成一个结果对
        for (int i = 0; i < arr.length; i++) {
            if (map.containsKey(target - arr[i])) { //
                result[0] = i;
                result[1] = map.get(target - arr[i]);
                break;
            }
            map.put(arr[i], i);
        }
        return result;
    }
}
